package com.sunpy.permissionservice.login.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.sunpy.permissionservice.bo.MenuBO;
import com.sunpy.permissionservice.bo.RoleBO;
import com.sunpy.permissionservice.bo.UserBO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
@NoArgsConstructor
public class LoginUserDetailBO implements UserDetails {

    private UserBO userBO;

    private List<RoleBO> roleBOList;

    @JsonIgnore
    private List<SimpleGrantedAuthority> authorities;

    public LoginUserDetailBO(UserBO userBO, List<RoleBO> roleBOList) {
        this.userBO = userBO;
        this.roleBOList = roleBOList;
    }

    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(authorities != null){
            return authorities;
        }

        authorities = new ArrayList<>();
        //把permission中String类型的权限信息封装成SimpleGrantedAuthority对象
        roleBOList.stream().forEach(roleBO -> {
            roleBO.getMenuBOList().forEach(menuBO -> {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(menuBO.getMenuCode());
                authorities.add(authority);
            });
        });

        return authorities;
    }

    public String getPassword() {
        return userBO.getPassword();
    }

    public String getUsername() {
        return userBO.getUserName();
    }

    public boolean isAccountNonExpired() {
        return true;
    }

    public boolean isAccountNonLocked() {
        return true;
    }

    public boolean isCredentialsNonExpired() {
        return true;
    }

    public boolean isEnabled() {
        return true;
    }
}
